package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.MenuMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleDao;
    @Autowired
    MenuMapper menuDao;
    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        Page<Role> roles = roleDao.findByCondition(queryString);
        long total = roles.getTotal();
        List<Role> result = roles.getResult();
        return new PageResult(total, result);
    }
    @Override
    public void edit(Integer[] ids, List<Integer> users, Role role) {
        Set<Integer> ids1 = getIds(ids);
        roleDao.deteleRoleAndMenu(role.getId());
        roleDao.deteleRoleAndPermission(role.getId());
        roleDao.edit(role);
        setRoleAndMenuAndPermission(ids1,role.getId(),users);

    }
    @Override
    public void add(Integer[] ids, List<Integer> users, Role role) {
        Set<Integer> ids1 = getIds(ids);
        roleDao.add(role);
        setRoleAndMenuAndPermission(ids1,role.getId(),users);

    }

    @Override
    public void delete(Integer id) {
        roleDao.deteleRoleAndMenu(id);
        roleDao.deteleRoleAndPermission(id);
        roleDao.deteleRole(id);

    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }




    public  void setRoleAndMenuAndPermission(Set<Integer> menuId,Integer roleId,List<Integer> permissionId) {
        for (Integer id : menuId) {
            roleDao.setRoleAndMenu(roleId,id);
        }
        for (Integer id : permissionId) {
            roleDao.setRoleAndPermission(roleId,id);
        }

    }



    public  Set<Integer> getIds(Integer[] ids) {
        Set set=new HashSet();
        for (Integer id : ids) {
           Menu menu = menuDao.findById(id);
           if(menu.getParentMenuId()!=null){

              set.add(menu.getParentMenuId());
           }
            set.add(id);
        }
        return set;
    }
}
